<?php
// https://github.com/serpro/Android-PHP-Encrypt-Decrypt
/*
Encryption Java
  String encryptedRequest = ApiCrypter.bytesToHex(this.apiCrypter.encrypt(jsonParams.toString()));
Encryption PHP
  $encrypted = $ApiCrypter->encrypt($str);

Decryption Java
  String res = new String( this.apiCrypter.decrypt( text ), "UTF-8" );
  res = URLDecoder.decode(res,"UTF-8");
Decryption PHP
  $decrypted = $ApiCrypter->decrypt($str);
*/

require_once ("C_krn_audit.php");

class ApiCrypter
{
        private $iv = IV; #Same as in JAVA
        private $key = SEMILLA_JAVA; #Same as in JAVA

// Evitamos el clonaje del objeto. Patrón Singleton
	private function __clone() {
	}
	
	private function __wakeup() {
	}
	
	private static $_instance;
	
	public static function getInstance() {
		if (! (self::$_instance instanceof self)) {
			self::$_instance = new self ();
		}
		
		return self::$_instance;
	}

        function __construct()
        {
        		global $cAUDIT;
		$cAUDIT->AddAudit ( AUDIT_EXTEND, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, "::constructor (" . __CLASS__ . ")" );
        }

        function encrypt($str) {
          global $cAUDIT;
          		  global $IDIOMA, $language;
          $cAUDIT->AddAudit ( AUDIT_APP, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $language [$IDIOMA] [107]);
          $iv = $this->iv;

          $td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);

          mcrypt_generic_init($td, $this->key, $iv);
          $encrypted = mcrypt_generic($td, utf8_decode($str));

          mcrypt_generic_deinit($td);
          mcrypt_module_close($td);

          return bin2hex($encrypted);
        }

        function decrypt($code) {
        global $cAUDIT;
        		  global $IDIOMA, $language;
          $cAUDIT->AddAudit ( AUDIT_APP, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $language [$IDIOMA] [108] );
          $code = $this->hex2bin($code);
          $iv = $this->iv;

          $td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);

          mcrypt_generic_init($td, $this->key, $iv);
          $decrypted = mdecrypt_generic($td, $code);

          mcrypt_generic_deinit($td);
          mcrypt_module_close($td);

          return utf8_encode(trim($decrypted));
        }

        protected function hex2bin($hexdata) {
          $bindata = '';

          for ($i = 0; $i < strlen($hexdata); $i += 2) {
                $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
          }

          return $bindata;
        }
        
}


// Instancia de la clase
// $BD = new c_MySQLDB;
try {
	$AC = ApiCrypter::getInstance ();
} catch ( Exception $e ) {
	global $cAUDIT;
	global $IDIOMA, $language;
	
	$cAUDIT->AddAudit ( AUDIT_EXTEND, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $language [$IDIOMA] [2] . $e->getMessage () );
	
	
	
}

?>
